package com.zzz.springsecuritystudy.service;

import com.zzz.springsecuritystudy.entity.AuthUserDto;
import com.zzz.springsecuritystudy.entity.ResponseResult;
import com.zzz.springsecuritystudy.entity.User;
import com.zzz.springsecuritystudy.util.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuzhizun
 * @date 2021/9/18
 */
@Service
public class AuthServiceImpl implements  AuthService{

    @Resource
    private AuthenticationManagerBuilder authenticationManagerBuilder;

    public Map<String, Object> login(AuthUserDto authUser){
        // 封装用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(authUser.getUsername(), authUser.getPassword());
        // 去判断是否密码正确 UserDetailsService的loadUserByUsername方法
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);

        // 将认证信息放在上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成token
        String token = JwtUtils.createToken(authentication, 60 * 1000 * 60);
        // 将生成的token  放入redis中   username  -------> token

        // 获取用户信息
        User principal = (User) authentication.getPrincipal();
        // 返回 token 与 用户信息
        Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
            put("token",token);
            put("user", principal);
        }};

        return authInfo;
    }
}
